package edu.zjut.hjg.saas.biz.service.impl;

import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import edu.zjut.hjg.saas.biz.service.EmailService;

/**
 * @description 发送邮件服务实现
 * @author jinggang.huangjg
 * @date 2010-2-23
 * @version 1.0
 */
public class EmailServiceImpl implements EmailService {

    public static Log      log = LogFactory.getLog(EmailServiceImpl.class);

    private JavaMailSender mailSender;                                     // 邮件发送器

    private TaskExecutor   taskExecutor;                                   // 异步执行器

    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void setTaskExecutor(TaskExecutor taskExecutor) {
        this.taskExecutor = taskExecutor;
    }

    @Override
    public void sendEmail(final String to, final String subject, final String content) {
        if (log.isInfoEnabled()) {
            log.info("sendEmail:to=" + to + ",subject=" + subject + ",content=" + content);
        }
        taskExecutor.execute(new Runnable() {

            @Override
            public void run() {
                // 建立邮件讯息
                MimeMessage mailMessage = mailSender.createMimeMessage();
                MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage);

                // 设定收件人、寄件人、主题与内容
                try {
                    messageHelper.setTo(to);
                    messageHelper.setSubject(subject);
                    messageHelper.setText(content, true);
                } catch (Exception e) {
                    log.error("send email error:to=" + to + ",subject=" + subject + ",content="
                            + content, e);
                }
                // 发送邮件
                mailSender.send(mailMessage);
            }
        });
    }
}
